import { Component, OnInit } from '@angular/core'
import { FormGroup, FormBuilder, Validators } from '@angular/forms'
import { I18NService } from '@core'
import { take, tap } from 'rxjs/operators'
import { NzMessageService } from 'ng-zorro-antd'

import { NewPageAccessor } from '@shared/components/new-page/new-page.interface'
import { IBiz } from '@shared/interfaces/biz'
import { makeAllControlDirty } from 'app/utils/helpers'
import { ManualAuthDataService } from '../../manual-auth-data.service'
import { IManualAuthCollection } from '@shared/interfaces/manualAuth'
import { IAamsRequired, IAamsItem } from '@shared/components/aams-select/aams-select.interface'
import {
  getAAMSAcquirer,
} from 'app/utils/helpers'
import { SettingsService } from '@delon/theme'
import { User } from '@shared/interfaces/user'
@Component({
  selector: 'app-manual-auth-new-system',
  templateUrl: './system.component.html',
  styleUrls: ['../../../../../shared/styles/new-page-form.less'],
})
export class ManualAuthNewSystemComponent implements NewPageAccessor, OnInit {
  constructor(
    private fb: FormBuilder,
    private msg: NzMessageService,
    private i18n: I18NService,
    private dataService: ManualAuthDataService,
    public settings: SettingsService,
  ) {}

  data: any
  payload: IBiz = {}
  form: FormGroup = this.fb.group({})
  required: IAamsRequired = {
    acquirer: true,
    group: false,
    merchant: false,
  }
  authUser: User
  chosenAcquirer: IAamsItem
  ngOnInit() {
    this.authUser = this.settings.user as User
    this.chosenAcquirer = getAAMSAcquirer(this.authUser as User)
    this.dataService.manualAuthData$.value$
      .pipe(
        tap(data => {
          this.form = this.fb.group({
            biz: [data, [Validators.required]],
          })
        }),
        take(1),
      )
      .subscribe()
  }

  checkValid(): boolean {
    if (!this.form.valid) {
      makeAllControlDirty(this.form)
      return false
    }

    if (!this.form.get('biz').value.insCode) {
      if (!this.chosenAcquirer.num) {
        const msg = this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.BIZ_LEVEL.INSTITUTION')})
        this.msg.error(msg)
        return false
      }
    }

    if (!this.form.get('biz').value.intStoreCode) {
      const msg = this.trans('VALIDATION.REQUIRED_SELECT', { name: this.trans('GENERAL.BIZ_LEVEL.STORE')})
      this.msg.error(msg)
      return false
    }

    this.pushDataToStore()
    this.msg.success(this.trans('GENERAL.NOTIFICATION.VALIDATION_SUCCESS'))
    return true
  }

  pushDataToStore(): void {
    const data: IManualAuthCollection = this.form.get('biz').value
    if (!!this.chosenAcquirer.num) {
      const { insCode, insName, insNameEN } = this.authUser
      Object.assign(data, { insCode, insName, insNameEN })
    }
    this.dataService.setManualAuthData(data)
  }

  private trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
